package everyday;

import CommonStructure.TreeNode;

public class T1026 {
    int max = 0;

    public int maxAncestorDiff(TreeNode root) {
        dfs(root);
        return max;
    }

    public int[] dfs(TreeNode father) {
        int fv = father.val;
        int[] left = new int[]{fv, fv};
        int[] right = new int[]{fv, fv};
        if (father.left != null) {
            left = dfs(father.left);
            getMax(left, fv);
        }
        if (father.right != null) {
            right = dfs(father.right);
            getMax(right, fv);
        }
        return add(left, right, fv);
    }

    public void getMax(int[] range, int a) {
        max = Math.max(max, Math.max(Math.abs(range[0] - a), Math.abs(range[1] - a)));
    }

    public int[] add(int[] left, int[] right, int fv) {
        return new int[]{Math.min(fv, Math.min(left[0], right[0])), Math.max(fv, Math.max(left[1], right[1]))};
    }

}
